<template>
  <div class="box">
    <div class="content">
      <el-row>
        <el-button icon="el-icon-plus" size="small" type="primary" @click="add">新增</el-button>
      </el-row>
      <div class="table" style="margin-top: 25px;">
        <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="categoryId" border
        :cell-style="{ textAlign: 'center' }"
        :default-expand-all="false" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="categoryName" label="分类名称"  width="130" header-align="center">
          </el-table-column>
          <el-table-column prop="pic" label="图片" width="250" header-align="center">
            <template slot-scope="scope">
              <img :src="scope.row.pic" alt="" style="max-width: 100%; max-height: 100px; width: 200px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="248" header-align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 1">正常</el-tag>
              <el-tag v-if="scope.row.status == 0" type="danger">下线</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="seq" label="排序号" width="248" header-align="center">
          </el-table-column>
          <el-table-column label="操作" width="248" header-align="center">
            <template slot-scope="scope">
              <el-button size="small " type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button size="small " type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="addlist">
        <el-dialog title="新增" :visible.sync="dialogFormVisible">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="分类图片" :label-width="formLabelWidth">
              <el-upload class="avatar-uploader" action="http://47.104.167.34:9305/apis/admin/file/upload/element"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{
                  'Authorization': '9Vm+AV0n4lnb8KEe8Q68CdwJmkXTXvkvgrWeqbDci2G2e/M4t9XzsG9C1YX0pbUN'
                }">
                <img v-if="ruleForm.pic" :src="ruleForm.pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="ruleForm.categoryName"></el-input>
            </el-form-item>
            <el-form-item label="排序号" prop="">
              <el-input-number v-model="ruleForm.seq" @change="handleChange1" :min="1" label="描述文字"></el-input-number>
            </el-form-item>
            <el-form-item label="上级分类" prop="">
              <el-cascader v-model="value" :options="options" clearable
                :props="{ value: 'categoryId', checkStrictly: true, label: 'categoryName', children: 'children', expandTrigger: 'hover' }"
                @change="handleChange2"></el-cascader>
            </el-form-item>
            <el-form-item label="状态" prop="">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="0">下线</el-radio>
                <el-radio :label="1">正常</el-radio>

              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="show1">取 消</el-button>
            <el-button type="primary" @click="show2">确 定</el-button>
          </div>
        </el-dialog>
      </div>

      <div class="edit">
        <el-dialog title="修改" :visible.sync="dialogFormVisible2">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="分类图片" :label-width="formLabelWidth">
              <el-upload class="avatar-uploader" action="http://47.104.167.34:9305/apis/admin/file/upload/element"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="{
                  'Authorization':this.token
                }">
                <img v-if="ruleForm2.pic" :src="ruleForm2.pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="ruleForm2.categoryName"></el-input>
            </el-form-item>
            <el-form-item label="排序号" prop="">
              <el-input-number v-model="ruleForm2.seq" @change="handleChange3" :min="1" label="描述文字"></el-input-number>
            </el-form-item>
            <el-form-item label="上级分类" prop="">
              <el-cascader v-model="ruleForm2.value" :options="options" clearable
                :props="{ value: 'categoryId', checkStrictly: true, label: 'categoryName', children: 'children', expandTrigger: 'hover' }"
                @change="handleChange4"></el-cascader>
            </el-form-item>
            <el-form-item label="状态" prop="">
              <el-radio-group v-model="ruleForm2.status">
                <el-radio :label="0">下线</el-radio>
                <el-radio :label="1">正常</el-radio>

              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="show3">取 消</el-button>
            <el-button type="primary" @click="show4">确 定</el-button>
          </div>
        </el-dialog>
      </div>


    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      token:localStorage.getItem('token'),
      value: [],
      options: [],
      tableData: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      formLabelWidth: '100px',
      // value2:[],
      ruleForm: {
        categoryName: '',
        seq: 1,
        pic: '',
        status: 1,
        grade: '',
        parentId: '',
        t: Date.now(),
      },
      ruleForm2: {
        pic: '',
        categoryName: '',
        seq: 1,
        value2: [],
        status: 1,
        grade: '',
        parentId: '',
        t: Date.now(),
      },
      rules: {
        categoryName: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
        ],
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    cellStyle() {
      return 'text-align: center;';
    },
    show1() {
      this.dialogFormVisible = false
    },
    show2() {
      this.$axios({
        method: 'post',
        url: `/api/prod/category`,
        headers: {
          'Authorization': localStorage.getItem('token')
        },
        data: {
          ...this.ruleForm
        }
      })
        .then((res) => {
          console.log(res);
          if (res.data.code == '00000') {
            this.$message({
              type: 'success',
              message: '新增成功!'
            });
            this.getList()
            this.dialogFormVisible = false
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }


        })

      console.log(this.value);

    },

    show3() {
      this.dialogFormVisible2 = false
    },
    show4() {
      this.$axios({
        method: 'put',
        url: `/api/prod/category`,
        headers: {
          'Authorization': localStorage.getItem('token')
        },
        data: {
          categoryId:this.ruleForm2.categoryId,
          categoryName:this.ruleForm2.categoryName,
          grade:this.ruleForm2.grade,
          parentId:this.ruleForm2.parentId,
          pic:this.ruleForm2.pic,
          seq:this.ruleForm2.seq,
          status:this.ruleForm2.status,
          t:Date.now()
        }
      }).then((res)=>{
        console.log(res);
        if (res.data.code == '00000') {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.getList()
            this.dialogFormVisible2 = false
          } else {
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          }
      })
      
    },
    add() {
      this.ruleForm.categoryName = ""
      this.ruleForm.seq = 1
      this.ruleForm.pic = ""
      this.ruleForm.status = 1

      this.dialogFormVisible = true
    },
    getList() {
      this.$axios({
        method: 'get',
        url: `/api/prod/category/table?t=${Date.now()}`,
        headers: {
          'Authorization': localStorage.getItem('token')
        }
      })
        .then((res) => {
          console.log(res);
          const data = res.data.data;
          this.tableData = this.buildTree(data);
          this.options = this.buildTree(data)


        })
        .catch((error) => {
          console.error('获取数据失败', error);
          this.$message.error('获取数据失败，请检查网络或稍后重试');
        });
    },

    // 构建树形结构
    buildTree(data) {
      const map = {};
      const roots = [];

      // 首先将所有节点存储到 map 中
      data.forEach(item => {
        map[item.categoryId] = { ...item }; // 先不初始化 children
      });

      // 遍历数据，将子节点放入对应的父节点中
      data.forEach(item => {
        if (item.parentId !== 0) {
          // 如果父节点不存在 children，则初始化
          if (!map[item.parentId].children) {
            map[item.parentId].children = [];
          }
          map[item.parentId].children.push(map[item.categoryId]);
        } else {
          roots.push(map[item.categoryId]);
        }
      });

      // 移除没有子节点的 children 属性
      const removeEmptyChildren = (node) => {
        if (node.children && node.children.length === 0) {
          delete node.children; // 移除空的 children 属性
        } else if (node.children) {
          node.children.forEach(removeEmptyChildren); // 递归处理子节点
        }
      };

      roots.forEach(removeEmptyChildren); // 处理根节点
      return roots;
    },

    // 删除弹框
    open() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.$axios({
        method: 'get',
        url: `/api/prod/category/info/${row.categoryId}`,
        headers: {
          'Authorization': localStorage.getItem('token')
        },
        data: {
          t: Date.now(),
        }
      }).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.ruleForm2 = res.data.data;

          // 如果接口返回了 parentIds，直接赋值
          if (this.ruleForm2.parentIds && this.ruleForm2.parentIds.length > 0) {
            this.ruleForm2.value = this.ruleForm2.parentIds;
          } else {
            // 如果接口没有返回 parentIds，根据 parentId 和 grade 动态生成层级路径
            this.ruleForm2.value = this.generateParentIds(this.ruleForm2.parentId, this.options);
          }

          this.dialogFormVisible2 = true;
        }
      });
    },
    generateParentIds(parentId, options) {
      const findPath = (node, targetId, path) => {
        if (node.categoryId === targetId) {
          path.push(node.categoryId);
          return path;
        }
        if (node.children) {
          for (let child of node.children) {
            const result = findPath(child, targetId, [...path, node.categoryId]);
            if (result) return result;
          }
        }
        return null;
      };

      for (let option of options) {
        const path = findPath(option, parentId, []);
        if (path) return path;
      }
      return [];
    },
    handleChange1(value) {
      console.log(value);
    },
    handleChange2(value) {
      console.log(value);
      this.ruleForm.grade = value.length
      this.ruleForm.parentId = value[value.length - 1]
    },
    handleChange3(value) {
      console.log(value);
    },
    handleChange4(value) {
      console.log(value);
      this.ruleForm2.grade = value.length
      this.ruleForm2.parentId = value[value.length - 1]
    },
    handleDelete(index, row) {
      console.log(index, row);

      this.$confirm('确定执行删除操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'DELETE',
          url: `/api/prod/category/${row.categoryId}`,
          headers: {
            'Authorization': localStorage.getItem('token')
          }
        })
          .then((res) => {
            console.log(res);
            if (res.data.code == '00000') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }

          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.pic = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style scoped>
.box {
  width: 96%;
  padding: 10px 15px 15px;
  background-color: #f8f5f5;

  .content {
    padding: 15px;
    background-color: white;
  }
}

::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>